package com.findbus.activity;

import java.util.List;

import com.findbus.fragment.BaseFragment;
import com.util.tool.FragmentChangeHelper;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public abstract class BaseActivity extends FragmentActivity {

	protected FragmentManager manager;
	protected FragmentTransaction trasaction;
	protected BaseFragment oldFragment;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		initFragmentManager();
	}

	protected String showFragment(int layout, FragmentChangeHelper<BaseFragment> fragmentHelper) {
		BaseFragment fragment = fragmentHelper.getTargetFragment();
		trasaction = manager.beginTransaction();
		List<android.support.v4.app.Fragment> fragmentList = manager.getFragments();
		if (oldFragment != null && oldFragment.isVisible())
			trasaction.hide(oldFragment);
		else if (fragmentList != null && fragmentList.size() > 0)
			for (int i = fragmentList.size() - 1; i >= 0; i--) {
				BaseFragment f = (BaseFragment) fragmentList.get(i);
				if (f != null && f.isVisible()) {
					trasaction.hide(f);
					break;
				}
			}

		BaseFragment baseFragment = (BaseFragment) manager.findFragmentByTag(fragmentHelper.getTargetFragmentTag());
		if (baseFragment != null) {
			fragment = baseFragment;
			trasaction.show(fragment);
		} else {
			trasaction.add(layout, fragment, fragmentHelper.getTargetFragmentTag());
			trasaction.addToBackStack(fragment.getStackTagrget());
		}
		trasaction.commit();
		oldFragment = fragment;
		return fragment.getStackTagrget();
	}

	public void initFragmentManager() {
		manager = getSupportFragmentManager();
	}
}
